package com.ztjava.core.interceptor;

import java.util.Map;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.ztjava.core.Constant;
import com.ztjava.core.Jsub;
import com.ztjava.core.annotation.ControllerClass;
import com.ztjava.core.annotation.CustomTemplate;
import com.ztjava.core.client.AdminClient;
import com.ztjava.core.client.Client;
import com.ztjava.core.tool.ViewTool;
import com.ztjava.ext.auth.tool.AuthTool;

public class CoreInterceptor implements Interceptor{
	
	@Override
	public void intercept(Invocation inv) {
		//适合与某些第三方个性系统集成
		if(Jsub.core_interceptor_custom){
			inv.invoke();
		}else {
			String pre_path = null;
			String returnType = null;
			String skin = null;
			if(inv.getController().getClass().isAnnotationPresent(ControllerClass.class)){
				try {
					Client client = (Client)inv.getController().getClass().getAnnotation(ControllerClass.class).client().newInstance();
					returnType = client.getReturnType();
					pre_path = client.getNamespace();
					skin = client.getSkin();
					if(pre_path.equals("/")) pre_path = "";
					inv.getController().setAttr(Constant.PRE_PATH, pre_path);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			Ret authResult = AuthTool.check(inv);
			if(!authResult.getStr(Constant.RESULT).equals(Constant.SUCCESS)){
				switch (authResult.getStr(Constant.RESULT)) {
					case Constant.TIMEOUT:
						if(returnType.equals(Constant.json)||Constant.XMLHttpRequest.equals(inv.getController().getRequest().getHeader(Constant.XRequestedWith))){
							if(skin!=null&&skin.equals(AdminClient.skin)){
								inv.getController().setAttr(Constant.RESULT, Constant.TIMEOUT);
								inv.getController().renderJson(new String[]{Constant.RESULT});
							}else {
								inv.getController().setAttr(Constant.RESULT, Constant.TIMEOUT);
								inv.getController().setAttr(Constant.MESSAGE,authResult.getStr(Constant.MESSAGE));
								inv.getController().renderJson(new String[]{Constant.RESULT,Constant.MESSAGE});
							}
						}else {
							try{
								String loginUrl = Jsub.path+pre_path+"/auth";
								//自动进行微信登录跳转，减少一次页面跳转
								if(ViewTool.param("AUTH_"+authResult.getStr("portal")+"_THIRD_WEIXIN_ONOFF").equals("ON")){
									loginUrl = loginUrl + "/weixin";
								}
								loginUrl = loginUrl + "/login?redirect="+getRedirectUrl(inv);
								inv.getController().getResponse().sendRedirect(loginUrl);
							}catch (Exception e){
								e.printStackTrace();
							}
							inv.getController().renderNull();
						}
						return;
					case Constant.ERROR:
						if(returnType.equals(Constant.json)||Constant.XMLHttpRequest.equals(inv.getController().getRequest().getHeader(Constant.XRequestedWith))){
							inv.getController().setAttr(Constant.RESULT, Constant.ERROR);
							inv.getController().setAttr(Constant.MESSAGE,authResult.getStr(Constant.MESSAGE));
							inv.getController().renderJson(new String[]{Constant.RESULT,Constant.MESSAGE});
						}else {
							inv.getController().renderText(authResult.getStr(Constant.MESSAGE));
						}
						return;
					default:
						break;
				}
			}
			//处理自定义模板
			if(inv.getMethod().isAnnotationPresent(CustomTemplate.class)){
				String view = inv.getMethod().getAnnotation(CustomTemplate.class).value();
				Cache cache = Redis.use();
				if(cache.hexists(Constant.R_TEMPLATE, inv.getActionKey())){
					view = cache.hget(Constant.R_TEMPLATE, inv.getActionKey());
				}
				inv.getController().setAttr(Constant.CUSTOMTEMPLATE, view);
			}
			inv.invoke();
		}
	}
	
	private String getRedirectUrl(Invocation inv){
		String url = Jsub.path + inv.getActionKey();
		String paramStr = "";
		Map<String,String[]> params = inv.getController().getParaMap();
		for(String key:params.keySet()){
			String[] values = params.get(key);
			for(int i=0;i<values.length;i++){
				paramStr = paramStr + "%26"+key+"="+values[i];
			}
		}
		if(!paramStr.equals("")){
			url = url + "?"+paramStr.substring(3, paramStr.length());
		}
		return url;
	}
}
